package ks.server.controllers.commands.general.plugin;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.plugin.Plugin;
import ks.managers.plugin.PluginManager;
import ks.server.ServerContext;
import ks.server.ipc.Listener;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import java.net.MalformedURLException;
//TODO figure correct reponse format
/**
 * Server-side controller for processing an admin-command to request
 * a plugin's stats (wins/losses/date/suspension)
 * @author harry moreno
 *
 */
public class PluginInfoController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	/** regular expression indicating how to divide xml */
	String delims = "[/.]+";	//divides string by '/' and '.'
	
	/** Attributes from XML string. */
	public static final String pluginAtt = "plugin";
	
	public PluginInfoController (Communicator com) {
		this.com = com;
	}
	/** 
	 * plugin-clear Message comes in from Client.
	 * 
	 *  <plugin-info plugin="Heineman_Klondike"/>
	 * @throws MalformedURLException 
	 */
	public boolean process(Message m){
		Node pluginInfo = m.contents();
		
		// Find out plugin's name
		NamedNodeMap nnp = pluginInfo.getAttributes();
		
		Node pluginNode = nnp.getNamedItem(pluginAtt);
		String pluginName = pluginNode.getNodeValue();

		// Ask PluginManager for info on the plugin.
		try {
			PluginManager pm = ServerContext.getPluginManager();
			Plugin pluginToReq = pm.getPlugin(pluginName);
			
			if (pluginToReq != null) {
				// successful operation!
			} else {
				Listener.nack(m, 4, "Unable to clear Plugin");  // low severity level
			}
		
			// Broadcast plugins to everyone. Ask PluginManager for collection of plugins, 
			// and form this request from this set.
	        StringBuilder sb = new StringBuilder("<request version='1.0' id='1'><plugins>");
	        sb.append("<plugin name=\"" + pluginToReq.name + "\" uri=\"" + pluginToReq.location +
	        		"\" losses=\"" + pluginToReq.getLosses() + "\" wins=\"" + pluginToReq.getWins() +
	        		"\" date=\"" + pluginToReq.getDate() + "\" suspended=\"" + pluginToReq.getSuspended() +
	        		"\"/>\n");
	        
	        sb.append("</plugins></request>");
	        Document d = Message.construct(sb.toString());
	        
	        // send to the originator of the Message m.
	        Message r = new Message (d);
	        r.setRecipient(m.getOriginator());
	        
	        com.distribute(r);
	        return true;
		} catch (Exception e) {
			e.printStackTrace();

			return false;
		}
	}
}
